package series;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

public class SeasonDAO {

	@Autowired
	private JdbcTemplate db;
	
	@Autowired
	private EpisodeDAO episodeDAO;

	public SeasonDAO(JdbcTemplate db, EpisodeDAO episodeDAO) {
		super();
		this.db = db;
		this.episodeDAO = episodeDAO;
	}

	private static final class SeasonRowMapper implements
			ParameterizedRowMapper<Season> {

		@Override
		public Season mapRow(ResultSet rs, int rowNum) throws SQLException {
			Season entry = new Season(rs.getInt(1), rs.getInt(2), rs.getString(3),rs.getInt(4));
			return entry;
		}
	}
	
	public Season[] seasonsForSeries(int seriesId) {
		String sql = "select * from seasons where series_id='" + seriesId + "'";
		System.out.println(sql);
		List<Season> seasonsList = db.query(sql, new SeasonRowMapper());
		for (Season season : seasonsList) {
			List<Episode> episodes = episodeDAO.episodesForSeriesIdAndSeasonId(seriesId, season.getId());
			season.setEpisodes(episodes);
		}
		return seasonsList.toArray(new Season[]{});
	}
	
	
	public String seriesName() {
		String seriesIdSQL = "select name from seasons where id=1";
		String seriesId = db.queryForObject(seriesIdSQL,String.class);
		return seriesId;
	}
}
